﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using Stock.Model;
using HtmlAgilityPack;
using Stock.Util;

namespace Stock.Service
{
    public class AppService : BaseService
    {
        public AppService() : base(AppConst.GITEE_STOCK_URL)
        {

        }

        public async Task<AppUpdateModel> GetLastVersion()
        {
            var result = await GetStringAsync("/releases");
            string html = result.Flag ? result.Data : "";
            return ParseModel(html);
        }

        public async Task DownloadApp(string url, string saveFilePath, Action<double, double> downloadProcessing, Action<double> downlaodCompleted)
        {
            string dir = Path.GetDirectoryName(saveFilePath);
            if (!Directory.Exists(dir))
            {
                _ = Directory.CreateDirectory(dir);
            }
            if (File.Exists(saveFilePath))
            {
                File.Delete(saveFilePath);
            }
            _ = await DownloadFileAsync(url, saveFilePath, null, false, downloadProcessing, downlaodCompleted);
        }

        private AppUpdateModel ParseModel(string html)
        {
            AppUpdateModel model = new AppUpdateModel();
            if (string.IsNullOrEmpty(html))
            {
                return model;
            }
            try
            {
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(html);

                var root = doc.DocumentNode;
                var node = GetNode(root, "//div[@class='releases-timeline']/div[1]");
                if (node != null)
                {
                    string version = GetNodeText(node, "//div[@class='release-meta']/div[@class='tag-name']/a/span");
                    model.LastUpdateTime = GetNodeText(node, "//div[@class='release-meta']/div[@class='release-time']");
                    model.Version = StringUtil.GetVersion(version);
                    model.Name = GetNodeText(node, "//div[@class='release-body']/div[@class='release-header']/a");
                    string content = GetNodeText(node, "//div[@class='release-body']/div[3]/div[@class='markdown-body']");
                    var url = GetNodeAttrText(node, "//div[@class='release-body']/div[@class='footer']/div[@class='ui celled list releases-download-list']/div[1]/a", "href");
                    model.DownloadUrl = $"{AppConst.GITEE_HOME_URL}{url}";
                    if (!string.IsNullOrEmpty(content))
                    {
                        model.Content = content.Replace("&#x000A;", "\r\n");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            return model;
        }
    }
}
